import React from "react"
import {Link} from "react-router-dom"
import {Icon as LegacyIcon} from '@ant-design/compatible'
import {Menu} from "antd";
import {keySeparator, rootPath} from "../../../../shared/init"

const SubMenu = Menu.SubMenu
const MenuItem = Menu.Item

const permissionMenu = (menus, resources) => {
  return menus.map(m => {
      //无子菜单
      if (!m.children || m.children.length === 0) {
        if (m.component === undefined) {
          return null;
        } else {
          return resources.some(r => r.code === m.code || m.code === 'profile') ? m : null
        }
      }
      m.children = permissionMenu(m.children, resources)
      return m.children && m.children.length > 0 ? m : null
    }
  ).filter(m => !!m)
}


const itemIcon = (item) => {
  if (item.image) {
    return <img src={item.image} alt={''} className={'zr-menu-item-image'}/>
  }
  if (item.icon) {
    return <LegacyIcon type={item.icon}/>
  }
  if (item['iconClass']) {
    return <i className={`zr-menu-icon iconfont ${item['iconClass']}`}/>
  }
  return undefined
}

/**
 * 根据菜单数据生成菜单
 * @param menus
 * @param pKey
 * @param pRoute
 * */
const createMenus = (menus, pKey, pRoute) => {
  return menus.map(item => {
    const _key = pKey ? `${pKey}${keySeparator}${item.key}` : `${item.key}`
    const _route = `${pRoute}/${item.key}`

    const _label = (
      <span className="menu-item">
        {itemIcon(item)}
        <span>{item.label}</span>
      </span>
    )

    return item.children
      ? createSubMenu(item.children, _key, _route, _label)
      : createMenuItem(_label, _key, _route, item.param)
  })
}


/**
 * 生成子菜单
 * @param items
 * @param key
 * @param route
 * @param label
 * */
const createSubMenu = (items, key, route, label) => {
  return (
    <SubMenu title={label} key={`${rootPath}${keySeparator}${key}`}>
      {createMenus(items, key, route)}
    </SubMenu>
  )
}


/**
 * 生成菜单项
 * @param key
 * @param route
 * @param label
 * */
const createMenuItem = (label, key, route, param) => {
  const _mKey = param
    ? `${rootPath}${keySeparator}${key}${keySeparator}${param.value}`
    : `${rootPath}${keySeparator}${key}`

  return (
    <MenuItem key={_mKey}>
      {param
        ? <Link to={`/${route}/${param.value}`}>{label}</Link>
        : <Link to={`/${route}`}>{label}</Link>
      }
    </MenuItem>
  )
}

const menuSettings = {
  theme: "dark",
  style: {width: "100%"},
  mode: "inline",
  inlineCollapsed: true,
  inlineIndent: 20
}

export {
  createMenus,
  menuSettings,
  keySeparator,
  permissionMenu
}